package missObjects;

import java.io.BufferedReader;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.Statement;
import java.util.logging.Logger;

import db.RofDB;

/**
 * Handle the list of couple Airfield models/(ID airfield+IDFile) that are not
 * to be associated with takeoff/landing wpts criterion to be ignored : airfield
 * model = model AND (airfieldID and IDfile differents). Airfield ID and IDfile
 * = -1 => model always ignored Airfield ID and IDfile = ID of current airfield
 * => not ignored
 * 
 * @author lefuneste
 *
 */
public class FilteredAirfields {

	// private static List<String> ListOffilteredAirfields;
	/*
	 * private class airfieldInfo { String name; int fileID; int AirfieldID;
	 * 
	 * private void putinfDB() {
	 * 
	 * }
	 * 
	 * 
	 * }
	 */

	private static Logger LOGGER = Logger.getLogger("RofLogger");

	static {
		LOGGER.getUseParentHandlers();
	}

	/**
	 * add an airfield to the ignore list in DB
	 * 
	 * @param airfieldName
	 *            Name of the Airfield to ignore
	 */
	public void addAirfield(Connection con, String airfielmodel, int fileID,
			int airfieldID) {
		// TODO add an airfield to filter list in DB
	}

	/**
	 * @param airfieldName
	 *            Name of the Airfield to remove in DB
	 */
	public void removeAirfield(Connection con, String airfieldName, int fileID,
			int airfieldID) {
		// TODO remove an airfield of filter list in DB
	}

	/**
	 * init the list of filtered Airfield from the "filteredAirfield_init.csv"
	 * file and store it in DB
	 * 
	 * @throws Exception
	 */
	public static void init(Connection con) throws Exception {
		// Properties defaultProps = new Properties();
		String[] tabs = null;
		String line;
		boolean endFlag = false;

		Path path2file = Paths.get("filteredAirfield_init.csv");

		try (BufferedReader reader = Files.newBufferedReader(path2file,
				StandardCharsets.ISO_8859_1)) {
			// use of Transaction to improve SQLite performance
			RofDB.beginTransaction();

			do {
				line = reader.readLine();
				if (line == null) {
					endFlag = true;
					break;
				} else {
					tabs = line.split(";");
					int[] tabi = new int[2];
					tabi[0] = Integer.parseInt(tabs[1]);
					tabi[1] = Integer.parseInt(tabs[2]);
					// storage in DB
					try (Statement stmt = con.createStatement()) {
						String sql = "INSERT INTO AIRFIELDFILTER (name, fileID, airfieldID) VALUES('"
								+ tabs[0].toLowerCase()
								+ "','"
								+ tabi[0]
								+ "','" + tabi[1] + "');";
						stmt.executeUpdate(sql);
					}

				}
			} while (!endFlag);
			// end of use of Transaction to improve SQLite performance
			RofDB.endTransaction();

		} catch (Exception e) {
			LOGGER.severe(e.getClass().getName() + ": " + e.getMessage());
			throw (e);
		}
	}
}
